package config;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import resourse.ResourseMannager;

public class ClientConfig {
	private static final String PORT = "port";

	private static final String HOST = "host";


	private static final ClientConfig SERVER_CONFIG = new ClientConfig() ;

	private static final SAXReader SAR_READER = new SAXReader();

	private ClientConfig() {
		super();
	}

	public String host() throws DocumentException {
		return this.rootElement().element(HOST).getTextTrim().trim() ;
	}
	

	public int port() throws DocumentException {
		return Integer.parseInt(this.rootElement().element(PORT).getTextTrim().trim()) ;
	}
	
	public void changeConfig(String host,String port) throws DocumentException {
		String path=ServerConfig.class.getPackage().getName().replace(".", "/")+"/ClientConfig.xml";
		try{
			Document document = SAR_READER.read(new File(path));
			Element employee=document.getRootElement();    
			Element name= employee.element(PORT);
			name.setText(port); //添加Text值；例：<a>abc</a> 
			Element name1= employee.element(HOST);
			name1.setText(host); //添加Text值；例：<a>abc</a>  
			try{
				/** 将document中的内容写入文件中 */
				XMLWriter writer = new XMLWriter(new FileWriter(new File(path)));
				writer.write(document);
				writer.close();
				/** 执行成功,需返回1 */
			}catch(Exception ex){
				ex.printStackTrace();
			}         
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	

	private final Element rootElement() throws DocumentException {
		String path=ClientConfig.class.getPackage().getName().replace(".", "/")+"/ClientConfig.xml";
		return SAR_READER.read(new File(path)).getRootElement();
	}

	public static ClientConfig getInstance() {
		return SERVER_CONFIG ;
	}
	
	public void initClientConfig() {
		// TODO Auto-generated method stub
		String path=ClientConfig.class.getPackage().getName().replace(".", "/");
		File file=new File(path);    
		if  (!file .exists()  && !file .isDirectory())      
		{       
		    file .mkdir();    
		} 
		path += "/ClientConfig.xml";
		Document document = DocumentHelper.createDocument();  //创建文档   
		Element employee=document.addElement("miniserver");    
		Element name= employee.addElement(HOST);   //添加子节点 
		name.setText("ganlinux.eicp.net"); //添加Text值；例：<a>abc</a> 
		Element sex=employee.addElement(PORT);    
		sex.setText("8888");    
   
		try {    
			Writer fileWriter=new FileWriter(path);    
			XMLWriter xmlWriter=new XMLWriter(fileWriter);    
			xmlWriter.write(document);   //写入文件中 
			xmlWriter.close();   
		} catch (IOException e) {    
			System.out.println(e.getMessage());    
		}
	}
}
